﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NAudio.Midi;

namespace MidiPlayer
{
    class MidiSettingsViewModel
    {
        private bool Loaded = false;

        public MidiSettingsDto Settings;

        public String[] AvailableMidiIns;
        public String[] AvailableMidiOuts;

        public MidiSettingsViewModel(MidiSettingsDto set) { Settings = set;  }

        public void Load()
        {

            AvailableMidiIns = new string[MidiIn.NumberOfDevices];
            for (int device = 0; device < MidiIn.NumberOfDevices; device++)
            {
                AvailableMidiIns[device] = MidiIn.DeviceInfo(device).ProductName;
            }

            AvailableMidiOuts = new string[MidiOut.NumberOfDevices];
            for (int device = 0; device < MidiOut.NumberOfDevices; device++)
            {
                AvailableMidiOuts[device] = MidiOut.DeviceInfo(device).ProductName;
            }
            Loaded = true;

        }

        public int FindDevice(String DeviceName, bool IsInputDevice)
        {
            if (String.IsNullOrEmpty(DeviceName)) return -1;

            String[] array = IsInputDevice ? AvailableMidiIns : AvailableMidiOuts;
            for(int i = 0; i < array.Count(); i++)
            {
                if(array[i] == DeviceName) return i;
            }
            return -1;
        }

        public void Validate()
        {
            if(!Loaded) Load();

            if(FindDevice(Settings.MidiInName, true) == -1)
            {
                throw new ArgumentException("MIDI In (" + Settings.MidiInName + ") not found");
            }

            if (FindDevice(Settings.MidiOutName, false) == -1)
            {
                throw new ArgumentException("MIDI Out (" + Settings.MidiOutName + ") not found");
            }

        }

    }
}
